"""
MCP 演示启动脚本
同时启动服务器和客户端进行演示
"""
import asyncio
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor


def start_server():
    """启动MCP服务器"""
    print("🚀 启动 MCP Server...")
    try:
        subprocess.run([
            sys.executable, "-m", "uvicorn", 
            "mcp_server:app", 
            "--host", "0.0.0.0", 
            "--port", "8000",
            "--log-level", "info"
        ], check=True)
    except KeyboardInterrupt:
        print("\n⏹️  MCP Server 已停止")
    except Exception as e:
        print(f"❌ MCP Server 启动失败: {e}")


async def wait_for_server():
    """等待服务器启动"""
    import httpx
    
    print("⏳ 等待 MCP Server 启动...")
    for i in range(30):  # 最多等待30秒
        try:
            async with httpx.AsyncClient() as client:
                response = await client.get("http://localhost:8000/")
                if response.status_code == 200:
                    print("✅ MCP Server 已就绪")
                    return True
        except:
            pass
        
        await asyncio.sleep(1)
        print(f"   等待中... ({i+1}/30)")
    
    print("❌ 等待 MCP Server 启动超时")
    return False


async def run_client_demo():
    """运行客户端演示"""
    print("\n🎬 开始 MCP Client 演示...")
    
    # 等待服务器启动
    if not await wait_for_server():
        return
    
    # 运行客户端演示
    try:
        from mcp_client import MCPDemo
        demo = MCPDemo()
        await demo.run_demo()
    except Exception as e:
        print(f"❌ 客户端演示失败: {e}")


def main():
    """主函数"""
    print("🎉 MCP (Model Context Protocol) 完整演示")
    print("=" * 60)
    print("本演示将启动:")
    print("1. MCP Server (FastAPI服务器)")
    print("2. MCP Client (演示客户端)")
    print("=" * 60)
    
    # 使用线程池同时运行服务器和客户端
    with ThreadPoolExecutor(max_workers=2) as executor:
        # 启动服务器（在后台线程）
        server_future = executor.submit(start_server)
        
        # 等待一下让服务器启动
        time.sleep(2)
        
        try:
            # 运行客户端演示
            asyncio.run(run_client_demo())
        except KeyboardInterrupt:
            print("\n⏹️  演示被用户中断")
        except Exception as e:
            print(f"❌ 演示过程中出错: {e}")
        
        print("\n🏁 演示结束，正在关闭服务器...")
        
        # 注意: 在实际生产环境中，应该有更优雅的关闭机制
        import os
        import signal
        try:
            # 尝试优雅关闭
            os.system("taskkill /f /im python.exe 2>nul")  # Windows
        except:
            try:
                os.system("pkill -f uvicorn")  # Unix/Linux
            except:
                pass


if __name__ == "__main__":
    main() 